/**
 * @author Klaro
 */
var paint = false;
var canvas;
var context;
var canvasWidth = 500;
var canvasHeight = 300;
var clickX = new Array();
var clickY = new Array();
var clickColor = new Array();
var clickTool = new Array();
var clickSize = new Array();
var clickDrag = new Array();
var clickId = new Array();
var textArrayX = new Array();
var textArrayY = new Array();
var textArrayMessage = new Array();
var textArrayId = new Array();
var markerBackgroundImage = new Image();
var icon = false;
var iText=0;
function prepareCanvas() {
	// Create the canvas (Neccessary for IE because it doesn't know what a
	// canvas element is)
	var canvasDiv = document.getElementById('canvasDiv');
	canvas = document.createElement('canvas');
	canvas.setAttribute('position', 'absolute');
	canvas.setAttribute('width', canvasWidth);
	canvas.setAttribute('height', canvasHeight);
	canvas.setAttribute('id', 'canvas');
	canvasDiv.appendChild(canvas);
	if (typeof G_vmlCanvasManager != 'undefined') {
		canvas = G_vmlCanvasManager.initElement(canvas);
	}
	context = canvas.getContext("2d"); // Grab the 2d canvas context
	// Note: The above code is a workaround for IE 8 and lower. Otherwise we
	// could have used:
	// context = document.getElementById('canvas').getContext("2d");
	markerBackgroundImage.src = "images/standardBlackboard.png";
	context.drawImage(markerBackgroundImage, 0, 0, canvasWidth, canvasHeight);
	ajaxCall();
	freehand();
	$('#canvas').bind("ajaxStart", function() {
		// $(this).css('cursor','crosshair');
		}).bind("ajaxStop", function() {
		// $(this).css('cursor','move');
		});
}
function mkRandomString() {
	chars = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
			'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'z');
	charCount = chars.length;
	stringLength = 5;
	var outputString = '';
	var i = 0;
	do {
		random = Math.floor(Math.random() * charCount);
		random = chars[random];
		outputString += random;
		i++;
	} while (i < stringLength);
	return outputString;
}
function ajaxCall() {
	icon = true;
	// $('#canvas').css('cursor','crooshair');
	sendDataToServer();
	sendTextToServer();
	icon = false;
	// $('#canvas').css('cursor','move');
	setTimeout("ajaxCall()", 3000);
}
function addClick(x, y, dragging, id) {
	clickX.push(x);
	clickY.push(y);
	// clickTool.push(curTool);
	// clickColor.push(curColor);
	// clickSize.push(curSize);
	clickDrag.push(dragging);
	clickId.push(id);
}
function concatArrays(xDiff, yDiff, draggingDiff, idDiff) {
	clickX = clickX.concat(xDiff);
	clickY = clickY.concat(yDiff);
	clickDrag = clickDrag.concat(draggingDiff);
	clickId = clickId.concat(idDiff);
}
function clearCanvas() {
	context.fillStyle = '#ffffff'; // Work around for Chrome
	context.fillRect(0, 0, canvasWidth, canvasHeight); // Fill in the canvas
	// with white
	canvas.width = canvas.width; // clears the canvas
}
function redraw() {
	clearCanvas();
	context.drawImage(markerBackgroundImage, 0, 0, canvasWidth, canvasHeight);
	var i = 0;
	for (; i < clickX.length; i++) {
		context.beginPath();
		if (clickDrag[i] && i) {
			context.moveTo(clickX[i - 1], clickY[i - 1]);
		} else {
			context.moveTo(clickX[i], clickY[i]);
		}
		context.lineTo(clickX[i], clickY[i]);
		context.closePath();
		context.lineJoin = "round";
		context.strokeStyle = 'white';
		context.stroke();
	}
}
function sendDataToServer() {
	var params;
	params = "cordX=" + JSON.stringify(clickX) + "& cordY="
			+ JSON.stringify(clickY) + "& drag=" + JSON.stringify(clickDrag)
			+ "& id=" + JSON.stringify(clickId);
	$.ajax( {
		url : "test.php?action=sendtoserver",
		type : 'POST',
		async : true,
		cache : false,
		data : params,
		beforeSend : function() {
			// $('#canvas').css('cursor','crosshair');
	},
	complete : function() {
		// $('#canvas').css('cursor','crosshair');
		loadDataFromServer();
	},
	error : function() {
	},
	dataType : "json",
	success : function(data) {
	}
	});
}
function loadDataFromServer() {
	$.ajax( {
		url : "test.php?action=loadfromserver",
		type : 'POST',
		async : true,
		cache : false,
		beforeSend : function() {
		},
		complete : function() {
			// $('#canvas').css('cursor','move');
	},
	error : function() {
	},
	dataType : "json",
	success : function(data) {
		var arrayLengthDiff = clickX.length - data.length;
		var clickXDiff = new Array();
		var clickYDiff = new Array();
		var clickDragDiff = new Array();
		var clickIdDiff = new Array();
		if (arrayLengthDiff > 0) {
			clickXDiff = clickX.slice(-arrayLengthDiff);
			clickYDiff = clickY.slice(-arrayLengthDiff);
			clickDragDiff = clickDrag.slice(-arrayLengthDiff);
			clickIdDiff = clickId.slice(-arrayLengthDiff);
		}
		clickX = [];
		clickY = [];
		clickDrag = [];
		clickId = [];
		var i = 0;
		for (; i < data.length; i++) {
			// clickX.push(data[i].X);
		// clickY.push(data[i].Y);
		addClick(data[i].X, data[i].Y, Boolean(data[i].Drag), data[i].Id);
	}
	if (clickXDiff.length > 0) {
		concatArrays(clickXDiff, clickYDiff, clickDragDiff, clickIdDiff);
	}
	redraw();
}
	});
}
function snap() {
	if (paint == false) {
		$('#canvas')
				.bind(
						"mousemove",
						(function(e) {
							var mouseX = e.pageX - this.offsetLeft;
							var mouseY = e.pageY - this.offsetTop;
							var i = 0;
							for (; i < clickX.length; i++) {
								if (clickDrag[i] == false
										|| (clickDrag[i] == true && clickDrag[i + 1] == false)
										|| (clickDrag[i] == true && clickDrag[i + 1] === undefined)) {
									var tolerance = 5;
									var Xleft = parseInt(clickX[i]) - tolerance;
									var Xright = parseInt(clickX[i])
											+ tolerance;
									var Yup = parseInt(clickY[i]) - tolerance;
									var Ydown = parseInt(clickY[i]) + tolerance;
									if (mouseX <= Xright && mouseX >= Xleft
											&& mouseY <= Ydown && mouseY >= Yup) {
										$(this).css('cursor', 'crosshair');
										break;
									} else {
										$(this).css('cursor', 'auto');
									}
								}
							}
						}));
	}
}
function straightline() {
	$('#canvas').unbind('mousedown');
	$('#canvas').unbind('mousemove');
	$('#canvas').unbind('mouseup');
	$('#canvas').unbind('mouseleave');
	snap();
	$('#canvas').mousedown(function(e) {
		var mouseX = e.pageX - this.offsetLeft;
		var mouseY = e.pageY - this.offsetTop;
		addClick(mouseX, mouseY, paint, mkRandomString());
		redraw();
		paint = true;
	});
	$('#canvas').mousemove(
			function(e) {
				if (paint == true) {
					redraw();
					copyClickX = clickX;
					copyClickY = clickY;
					copyClickDrag = clickDrag;
					copyClickId = clickId;
					var mouseX = e.pageX - this.offsetLeft;
					var mouseY = e.pageY - this.offsetTop;
					context.moveTo(clickX[clickX.length - 1],
							clickY[clickX.length - 1]);
					context.lineTo(mouseX, mouseY);
					context.closePath();
					context.lineJoin = "round";
					context.strokeStyle = "white";
					context.stroke();
				}
			});
	$('#canvas')
			.mouseup(
					function(e) {
						var i = 0;
						var mouseX = e.pageX - this.offsetLeft;
						var mouseY = e.pageY - this.offsetTop;
						for (; i < clickX.length - 1; i++) {
							if (clickDrag[i] == false
									|| (clickDrag[i] == true && clickDrag[i + 1] == false)
									|| (clickDrag[i] == true && clickDrag[i + 1] === undefined)) {
								var tolerance = 5;
								var Xleft = parseInt(clickX[i]) - tolerance;
								var Xright = parseInt(clickX[i]) + tolerance;
								var Yup = parseInt(clickY[i]) - tolerance;
								var Ydown = parseInt(clickY[i]) + tolerance;
								if (mouseX <= Xright && mouseX >= Xleft
										&& mouseY <= Ydown && mouseY >= Yup) {
									paint = false;
									break;
								} else {
									paint = true;
								}
							}
						}
					});
	$('#canvas').dblclick(function(e) {
		paint = false;
	});
}
function freehand() {
	$('#canvas').unbind('mousedown');
	$('#canvas').unbind('mousemove');
	$('#canvas').unbind('mouseup');
	$('#canvas').unbind('mouseleave');
	$('#canvas').mousedown(function(e) {
		paint = true;
		var mouseX = e.pageX - this.offsetLeft;
		var mouseY = e.pageY - this.offsetTop;
		addClick(mouseX, mouseY, false, mkRandomString());
		redraw();
	});
	$('#canvas').mousemove(function(e) {
		if (paint == true) {
			var mouseX = e.pageX - this.offsetLeft;
			var mouseY = e.pageY - this.offsetTop;
			addClick(mouseX, mouseY, true, mkRandomString());
			redraw();
		}
	});
	$('#canvas').mouseup(function(e) {
		paint = false;
		// sendDataToServer();
		});

	$('#canvas').mouseleave(function(e) {
		paint = false;
		// sendDataToServer();
		});
	$('#canvas').mouseover(function(e) {
		/*
		 * if (icon=true) { $(this).css('cursor','crosshair'); } else {
		 * $(this).css('cursor','move'); }
		 */
	});
}
function text(){
	$('#canvas').unbind('mousedown');
	$('#canvas').unbind('mousemove');
	$('#canvas').unbind('mouseup');
	$('#canvas').unbind('mouseleave');
	$('#canvas').one("mousedown", function(e) {
		var mouseX = e.pageX - this.offsetLeft;
		var mouseY = e.pageY - this.offsetTop;
		var inputs = $("#canvasDiv").find('input');
		if (inputs.length!=0){
			iText=inputs.length;
		}
		$('#canvasDiv').append("<input id=" + iText + " type='text' size='5' style='font-family:Courier; position: absolute; z-index: 1; left:" + mouseX + "px; top:" + mouseY + "px; height:20px; background-color: transparent; border:1px dotted; color:white' value='this' />");
		var aa=$("#"+iText);
		addText(mouseX, mouseY, $("#"+iText)[0].value, $("#"+iText)[0].id);
		iText++;
	});
}
function addText(x, y, message, id){
	textArrayX.push(x);
	textArrayY.push(y);
	textArrayMessage.push(message);
	textArrayId.push(id);
}
function sendTextToServer() {
	var params;
	params = "textX=" + JSON.stringify(textArrayX)+ "& textY="
	+ JSON.stringify(textArrayY) + "& message=" + JSON.stringify(textArrayMessage)
	+ "& textid=" + JSON.stringify(textArrayId);
	$.ajax( {
		url : "test.php?action=texttoserver",
		type : 'POST',
		async : true,
		cache : false,
		data : params,
		beforeSend : function() {
	},
	complete : function() {
		loadTextFromServer();
	},
	error : function() {
	},
	dataType : "json",
	success : function(data) {
	}
	});
}
function loadTextFromServer() {
	$.ajax( {
		url : "test.php?action=loadtextfromserver",
		type : 'POST',
		async : true,
		cache : false,
		beforeSend : function() {
		},
		complete : function() {
			// $('#canvas').css('cursor','move');
	},
	error : function() {
	},
	dataType : "json",
	success : function(data) {
		var arrayLengthDiff = textArrayX.length - data.length;
		var textArrayXDiff = new Array();
		var textArrayYDiff = new Array();
		var textArrayMessageDiff = new Array();
		var textArrayIdDiff = new Array();
		if (arrayLengthDiff > 0) {
			textArrayXDiff = textArrayX.slice(-arrayLengthDiff);
			textArrayYDiff = textArrayY.slice(-arrayLengthDiff);
			textArrayMessageDiff = textArrayMessage.slice(-arrayLengthDiff);
			textArrayIdDiff = textArrayId.slice(-arrayLengthDiff);
		}
		var i = 0;
		for (; i < data.length; i++) {
			if (textArrayMessage[i]!=undefined && data[i].Message!=textArrayMessage[i]){
				data[i].Message=textArrayMessage[i];
			}
		}
		textArrayX = [];
		textArrayY = [];
		textArrayMessage = [];
		textArrayId = [];
		i=0;
		for (; i < data.length; i++) {
			addText(data[i].X, data[i].Y, data[i].Message, data[i].Id);
		}
		if (textArrayXDiff.length > 0) {
			concatArrays(textArrayXDiff, textArrayYDiff, textArrayMessageDiff, textArrayIdDiff);
		}
		$("#canvasDiv").find('input').remove();
		i=0;
		for (; i < textArrayX.length; i++) {
			$('#canvasDiv').append("<input id=" + textArrayId[i] + " type='text' style='font-family:Courier; position: absolute; z-index: 1; left:" + textArrayX[i] + "px; top:" + textArrayY[i] + "px; height:20px; background-color: transparent; border:1px dotted; color:white' value=" + textArrayMessage[i] + " />");
		}
		$("#canvasDiv :input").bind("keypress keydown",function(e) {
			//var charCode = e.which;
		    //var charStr = String.fromCharCode(charCode);
		    textArrayMessage[this.id]=this.value;
		    //this.size = this.value.length;
		    //var stophere=1;
		   });
	}
	});
}